<template>
	<view class="root-container">
		<view v-if="isLoaded" :class="hasComment ? 'item-container':'item-container item-margin-container'">
			<text class="item-title">{{blog.title}}</text>
			<text class="item-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-content"></rich-text>
			<image :src="blog.picture" mode="widthFix" class="img item-picture"></image>
			<view>
				<view v-for="(tag,index) in blog.tags" :key="index" class="item-tag"> {{tag}} </view>
			</view>
			<image :src="blog.user.avatar" mode="aspectFill" class="item-avatar"></image>
			<view class="icon-container">
				<image v-if="hasGood" src="../../static/icons/ic_good_fill.png" class="icon"
					@click.stop="changeGood(blog.id,false)"></image>
				<image v-else src="../../static/icons/ic_good.png" class="icon" @click.stop="changeGood(blog.id,true)">
				</image>
				<text class="icon-text">{{blog.good}}</text>
				<image src="../../static/icons/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="../../static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
		</view>
		<view v-if="hasComment" class="comments-container">
			<view v-for="(item,index) in parents" :key="item.id">
				<!-- 根评论和子评论的容器 -->
				<view class="cmt-container">
					<text class="cmt-author">{{item.nickName}}</text>
					<text class="cmt-time">{{item.createTime}}</text>
					<text class="cmt-content" @click="clickToReply(item)">{{item.content}}</text>
					<image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
				</view>
				<view v-if="replies[index].length>0" class="replies-container">
					<view class="reply-item" v-for="(reply,idx) in replies[index]" :key="reply.id">
						<view class="reply-info">
							<text class="reply-author">{{reply.nickName}}:</text>
							<text class="reply-to">@{{reply.toUser}}</text>
							<text class="reply-time">{{reply.createTime}}</text>
						</view>
						<text class="reply-content" @click="clickToReply(reply)">{{reply.content}}</text>
					</view>
				</view>
				<!-- 考虑间隔线 -->
				<view v-if="index < parents.length -1" class="cmt-line"></view>
			</view>
		</view>
		<view class="input-container">
			<image :src="avatar" mode="aspectFill" class="input-avatar" @click="clickToLogin"></image>
			<textarea v-model="inputValue" :placeholder="inputHolder" placeholder-class="input-holder" auto-height
				class="input-area" @input="inputGetComment" />
			<text class="iconfont icon-fasong input-commit" @click="clickCommit"></text>
		</view>
		<login-dialog ref="login" @after="afterLogin"></login-dialog>
	</view>
</template>

<script>
	let app = getApp()
	let parentId = null
	let cmtValue = ""
	export default {
		data() {
			return {
				blog: {},
				hasGood: false,
				isLoaded: false,
				hasComment: false,
				parents: [], //{c1},{c2},{c3},{}根评论集合
				replies: [], //[r1],[r2],[r3],[]子评论集合
				avatar: "../../static/icons/default_user.png",
				inputHolder: "请输入评论内容！",
				inputValue: ""
			}
		},
		onLoad(options) {
			let id = options.id
			// console.log(id)
			let good_ids = uni.getStorageSync(this.$params.key_good_ids)
			if (good_ids) {
				this.hasGood = good_ids.indexOf(id) >= 0
			}
			// this.getBlog(id)
			this.addReadCount(id)
			let prefix = app.globalData.token == 0 ? '' : this.$params.host
			this.avatar = prefix + app.globalData.avatar
			this.$noti.add(this.$params.noti_login_status, this, this.afterLogin)
		},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status)
		},
		methods: {
			clickCommit() {
				if (app.globalData.token.length == 0) {
					this.$refs.login.show()
					return
				}
				if (cmtValue.trim().length == 0) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return
				}
				let url = this.$params.host + this.$params.action_add_comment
				let data = {
					blog_id: this.blog.id,
					token: app.globalData.token,
					parent_id: parentId,
					nick_name: app.globalData.nickName,
					email: app.globalData.email,
					is_owner: app.globalData.uid == this.blog.user.id,
					content: cmtValue,
					avatar: "/" + app.globalData.avatar
				}
				this.$request.post(url, data, res => {
					console.log(res)
					let cmt = res.data
					// this.blog.comments.push(cmt)
					this.blog.comments = [...this.blog.comments, cmt]
					this.formatComments(this.blog.comments)
					this.hasComment = this.blog.comments.length > 0
					this.inputHolder = "请输入评论内容......"
					// this.inputValue = ""
					let pages = getCurrentPages()
					let prev = pages[pages.length - 2]
					prev.refreshComment(cmt)
					cmtValue = ""
					parentId = null
				})
			},
			clickToLogin() {
				this.$refs.login.show()
			},
			afterLogin(logout) {
				this.avatar = this.$params.host + app.globalData.avatar
			},
			inputGetComment(e) {
				cmtValue = e.detail.value
			},
			clickToReply(item) {
				parentId = item.id
				this.inputHolder = "@" + item.nickName
			},
			addReadCount(id) {
				let url = this.$params.host + this.$params.action_add_count
				let data = {
					id: id
				}
				this.$request.postParams(url, data, res => {
					let count = res.data.data
					// let pages = getCurrentPages()//a,b,c
					// let indexPage = pages[pages.length - 2]
					// indexPage.refreshCount(id, count)
					let args = {
						id: id,
						count: count
					}
					this.$noti.post(this.$params.noti_blog_count, args)
					console.log(count);
					this.getBlog(id)
				})
			},
			getBlog(id) {
				let url = this.$params.host + this.$params.action_blog + id
				this.$request.get(url, res => {
					let b = res.data.data
					uni.setNavigationBarTitle({
						title: b.user.nickName
					})
					if (!b.picture.startsWith('http')) {
						b.picture = this.$params.host + b.picture
					}
					if (!b.user.avatar.startsWith('http')) {
						b.user.avatar = this.$params.host + b.user.avatar
					}
					b.content = b.content.replace(/\<img/gi, 'img class="rich-img" ')
					b.createTime = this.$utils.formatTime(new Date(b.createTime))
					b.updataTime = this.$utils.formatTime(new Date(b.updataTime))
					this.blog = b
					this.isLoaded = true
					this.hasComment = b.comments.length > 0
					this.formatComments(b.comments)
				})
			},
			formatComments(comments) {
				if (comments.length == 0) {
					return
				}
				this.parents = []
				comments.forEach(item => {
					if (!item.avatar.startsWith("http")) {
						item.avatar = this.$params.host + item.avatar
					}
					item.createTime = this.$utils.formatTime(new Date(item.createTime))
					if (item.parentId == null) {
						this.parents.push(item)
					}
				})
				this.parents.sort(function(c1, c2) {
					return new Date(c2.createTime) - new Date(c1.createTime)
				})
				this.replies = new Array(this.parents.length).fill([])
				let index = 0
				this.parents.forEach(root => {
					let children = []
					children = children.concat(this.getAllChildren(root, comments))
					this.replies[index++] = children
					//过滤掉已经确定是某根评论子孙的这些评论
					comments = comments.filter(c => children.every(cc => cc.id != c.id))
				})
				// console.log(this.replies)
			},
			getAllChildren(root, comments) {
				let results = []
				comments.forEach(c => {
					if (c.parentId == root.id) {
						c.toUser = root.nickName
						results = results.concat(c)
						let cmts = comments.filter(cmt => cmt.id != c.id)
						let grandson = this.getAllChildren(c, comments)
						results = results.concat(grandson)
					}
				})
				return results
				//循环comments
				//每一个comment.parentId和root.id对比，若相等则comment是子评论
				//son就要放到结果集合里(所有的子和孙)
				//马上继续comment的子孙，let grandson = getAllChildren(son, comments)
				//把grandson放到results里面
			},
			changeGood(id, isGood) {
				this.hasGood = isGood
				if (isGood) {
					this.good_id.push(id)
				} else {
					let index = this.good_ids.indexOf(id)
					if (index > -1) {
						this.good_ids.splice(index, 1)
					}
				}
				uni.setStorageSync(this.$params.key_good_ids, this.good_ids)
				this.switchGood(id, isGood)
			},
			switchGood(id, isGood) {
				let action = isGood ? this.$params.action_good : this.$params.action_del_good
				let url = this.$params.host + action
				let data = {
					"id": id
				}
				this.$request.postParams(url, data, res => {
					this.blog.good = res.data.data
					this.blog.id = id
					let good_ids = this.good_ids
					let good = this.blog.good
					let args = {
						id: id,
						good: good,
						good_ids: good_ids
					}
					this.$noti.post(this.$params.noti_blog_good, args)
				})
			}

		}
	}
</script>


<style>
	@import url("blog.css");
</style>
